﻿using System;
using System.Collections.Specialized;
using System.Text;
using System.Net;
using System.IO;
using System.Configuration;
using System.Windows.Forms;
using System.Data;

using System.ComponentModel.Composition;
using EnergyService_CSharp;

namespace DatabasePlugin
{
    [Export(typeof(IEnergyMonitorPlugin))]
    public class DatabasePlugin : IEnergyMonitorPlugin
    {
        string dbType;
        string dbConn;
        EnergyReadingRepository repo;


        #region IEnergyMonitorPlugin Members

        public string Name
        {
            get { return "DatabasePlugin"; }
        }

        public string Description
        {
            get { return "Insert the reading data into a database"; }
        }

        public bool Enabled
        {
            get { return bool.Parse(GetSetting("databaseplugin_enabled", "false")); }
        }

        public bool Init()
        {
            dbType = GetSetting("databaseplugin_databasetype", "access"); 
            dbConn = GetSetting("databaseplugin_connectionstring", "");
            repo = new EnergyReadingRepository(dbType, dbConn);

            return true;
        }

        public bool Notify(EnergyReading rdg)
        {
            return repo.Save(rdg);
        }

        public bool DeInit()
        {
            return true;
        }

        public NameValueCollection Configure(NameValueCollection current)
        {
            NameValueCollection retVal = null;

            frmConfig frm = new frmConfig(current);
            DialogResult dlg = frm.ShowDialog();

            if (DialogResult.OK == dlg)
            {
                retVal = new NameValueCollection();
                retVal.Add("databaseplugin_enabled", frm.Enable.ToString().ToLower());
                retVal.Add("databaseplugin_connectionstring", frm.ConnectionString);
                retVal.Add("databaseplugin_databasetype", frm.DatabaseType);
            }
            return retVal;
        }

        #endregion


        private string GetSetting(string key, string defaultValue)
        {
            NameValueCollection appSettings = ConfigurationManager.AppSettings;
            string val = defaultValue;
            try
            {
                string v = appSettings.Get(key);
                if (null != v)
                {
                    val = v;
                }
            }
            catch
            {
                // just ignore
            }
            return val;
        }

    }
}
